package com.seed.application.exception;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotSafeException;
import com.seed.core.pojo.R;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@ControllerAdvice
public class GlobalException {
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public R<Object> handle(Exception e) {
        e.printStackTrace();
        if(e instanceof NotLoginException) {
            return R.result(401, "已超时，请重新登录");
        }

        if(e instanceof NotSafeException) {
            return R.result(402, "请输入密码提供二级认证");
        }

        if(e instanceof NotPermissionException) {
            return R.result(403, "没有访问权限");
        }

        if(e instanceof MethodArgumentNotValidException) {
            Map<String, String> errors = new HashMap<>();
            BindingResult result = ((MethodArgumentNotValidException) e).getBindingResult();
            List<FieldError> fieldErrorList = result.getFieldErrors();
            fieldErrorList.forEach(fieldError -> {
                errors.put(fieldError.getField(), fieldError.getDefaultMessage());
            });
            return R.result(500, fieldErrorList.get(0).getDefaultMessage(), errors);
        }
        return R.error(e.getMessage());
    }
}
